const User = require('../models/User.js');
const emailValidator = require('email-validator');

/**
 *  @desc 注册方法
 */
exports.createRegister = (req, res) => {
  const {email, password} = req.body;
  if (!email || !password) {
    return res.status(400).json({message: 'Email and password are required.'});
  }
  if (!emailValidator.validate(email)) {
    return res.status(400).json({message: 'Invalid email address.'});
  }

  // Check password length and complexity
  if (
    password.length > 256 ||
    password.length < 6 ||
    !password.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/)
  ) {
    return res
      .status(400)
      .json({message: '无效的密码。密码长度必须至少6个字符，最多256个字符，并包含数字、字母和特殊字符的组合。'});
  }

  User.register(new User({email, username: email}), password, (err, user) => {
    if (err) {
      console.error(err);
      return res.status(500).json({message: err.message});
    }

    res.status(201).json({message: 'User created successfully.'});
  });
};
